'use strict';
var config = require('../config.js');
var Promise = require('../utils/es6-promise.min.js');
var jwtDecode = require('../utils/jwt-decode.js');
var api = require('../utils/api.js');

/**
 * 请求服务 
 * method 请求的方法名(get post) 
 * request_data   (method -- api_url --  data)
 */
let request = function (request_data) {
  let that = this;
  return new Promise((resolve, reject) => {
    api[request_data.method](request_data.api_url, request_data.data)
      .then((data) => {
        if (data.code == 0) {
          console.log('success then=>',data.r);
          resolve(data.r);
        } else {
          console.log('reject then=>',data);
          reject(data);
        }
      })
      .catch(function (error) {
        console.log('catch',error);
        reject(error);
      })
  })
}

/**
 * 数据处理，默认了基本数据
 * open_id
 */
var addData = (api_url, data) => {
  var newData = Object.assign({}, data);
  newData.open_id = wx.getStorageSync('openid');
  return newData;
}


/**
 * 外放接口
 */
module.exports = {
  //获取open_id
  get_openid(res) {
    console.log(res);
    
    return api.request({
      method: "POST",
      api_url: config.api + "/iNews/getUserOpenIdByCode",
      data: {
        "app_id": config.appid,
        "code": res.code,
      },
      header: {
        // 'content-type': 'application/json',
        'content-type': 'application/x-www-form-urlencoded',
        
      },
      errorInfo: { code: 1002, msg: '获取openid失败' }
    })
    .then((data) => {
      res.open_id = data.r;
      return res;

    })
  },  

   //登录
  login(phone, code, userInfo) {
    var data = Object.assign({
      phone: phone,
      code: code,
      app_id: config.appid,
      open_id: wx.getStorageSync('openid'),
      alias: config.alias
    }, userInfo);
    return this.post("/login/customer/userAuth", data);

  },

  get(api_url, _data) {
    return request.call(this, {
      method: 'get',
      api_url: api_url,
      data: addData(api_url, _data)
    })
  },
  post(api_url, _data) {
    return request.call(this, {
      method: 'post',
      api_url: api_url,
      data: addData(api_url, _data)
    })
  }
}